package com.tianzeculture.stagebao.activity.artist;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.hys.utils.AppUtils;
import com.hys.utils.DensityUtils;
import com.hys.utils.ImageUtils;
import com.hys.utils.InitCacheFileUtils;
import com.hys.utils.SdcardUtils;
import com.tianzeculture.stagebao.R;
import com.tianzeculture.stagebao.activity.home.MainActivity;
import com.tianzeculture.stagebao.application.StageBaoApplication;
import com.tianzeculture.stagebao.base.BaseActivity;
import com.tianzeculture.stagebao.bean.User;
import com.tianzeculture.stagebao.net.ArtistRestUsage;
import com.tianzeculture.stagebao.network.Request;
import com.tianzeculture.stagebao.network.enity.MSG;
import com.tianzeculture.stagebao.network.util.DensityUtil;
import com.tianzeculture.stagebao.network.util.ToastUtil;
import com.tianzeculture.stagebao.publish.MyCallBack;
import com.tianzeculture.stagebao.publish.OnRecyclerItemClickListener;
import com.tianzeculture.stagebao.publish.PostArticleImgAdapter;
import com.tianzeculture.stagebao.util.StatusBarUtil;
import com.tianzeculture.stagebao.util.Util;
import com.tianzeculture.stagebao.view.GridSpacingItemDecoration;

import java.io.ByteArrayOutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by Administrator on 2018/7/2 0002.
 * 编辑个人代表作
 */

public class ArtistEditPersonWorkActivity extends BaseActivity {

    public static final String FILE_DIR_NAME = "com.kuyue.wechatpublishimagesdrag";//应用缓存地址
    public static final String FILE_IMG_NAME = "images";//放置图片缓存
    public static final int IMAGE_SIZE = 9;//可添加图片最大数
    private static final int REQUEST_IMAGE = 1002;

    private ArrayList<String> originImages;//原始图片
    private ArrayList<String> dragImages;//压缩长宽后图片
    private Context mContext;
    private PostArticleImgAdapter postArticleImgAdapter;
    private ItemTouchHelper itemTouchHelper;

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvRight)
    TextView tvRight;

    @BindView(R.id.rvPhoto)
    RecyclerView rcvImg;
    @BindView(R.id.tvDelete)
    TextView tv;//删除区域提示

    @Request
    ArtistRestUsage artistRestUsage = null;
    private int addRepresentativeWork = 101;


    private void initData() {
        originImages = getIntent().getStringArrayListExtra("imgs");
        if (originImages == null) {
            originImages = new ArrayList<>();
        }
        mContext = getApplicationContext();
        InitCacheFileUtils.initImgDir(FILE_DIR_NAME, FILE_IMG_NAME);//清除图片缓存
        //添加按钮图片资源
        String plusPath = getString(R.string.glide_plus_icon_string) + AppUtils.getPackageInfo(mContext).packageName + "/mipmap/" + R.mipmap.icon_shangchuan;
        dragImages = new ArrayList<>();
        originImages.add(plusPath);//添加按键，超过9张时在adapter中隐藏
        dragImages.addAll(originImages);
        new Thread(new MyRunnable(dragImages, originImages, dragImages, myHandler, false)).start();//开启线程，在新线程中去压缩图片
    }

    private void initView() {

        initRcv();
    }

    private void initRcv() {

        postArticleImgAdapter = new PostArticleImgAdapter(mContext, dragImages);
        rcvImg.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        rcvImg.addItemDecoration(new GridSpacingItemDecoration(3, DensityUtil.dp2px(
                ArtistEditPersonWorkActivity.this, 8), false));
        rcvImg.setAdapter(postArticleImgAdapter);
        MyCallBack myCallBack = new MyCallBack(postArticleImgAdapter, dragImages, originImages);
        itemTouchHelper = new ItemTouchHelper(myCallBack);
        itemTouchHelper.attachToRecyclerView(rcvImg);//绑定RecyclerView

        //事件监听
        rcvImg.addOnItemTouchListener(new OnRecyclerItemClickListener(rcvImg) {

            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                if (originImages.get(vh.getAdapterPosition()).contains(getString(R.string.glide_plus_icon_string))) {//打开相册
                    MultiImageSelector.create()
                            .showCamera(true)
                            .count(IMAGE_SIZE - originImages.size() + 1)
                            .multi()
                            .start(ArtistEditPersonWorkActivity.this, REQUEST_IMAGE);
                } else {
//                    ToastUtils.getInstance().show(StageBaoApplication.getInstance(), "预览图片");
                }
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                //如果item不是最后一个，则执行拖拽
                if (vh.getLayoutPosition() != dragImages.size() - 1) {
                    itemTouchHelper.startDrag(vh);
                }
            }
        });

        myCallBack.setDragListener(new MyCallBack.DragListener() {
            @Override
            public void deleteState(boolean delete) {
                if (delete) {
                    tv.setBackgroundResource(R.color.holo_red_dark);
                    tv.setText(getResources().getString(R.string.post_delete_tv_s));
                } else {
                    tv.setText(getResources().getString(R.string.post_delete_tv_d));
                    tv.setBackgroundResource(R.color.holo_red_light);
                }
            }

            @Override
            public void dragState(boolean start) {
                if (start) {
                    tv.setVisibility(View.VISIBLE);
                } else {
                    tv.setVisibility(View.GONE);
                }
            }

            @Override
            public void clearView() {

            }
        });
    }

    //------------------图片相关-----------------------------

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE && resultCode == RESULT_OK) {//从相册选择完图片
            //压缩图片
            new Thread(new MyRunnable(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT),
                    originImages, dragImages, myHandler, true)).start();
        }
    }

    /**
     * 另起线程压缩图片
     */
    static class MyRunnable implements Runnable {

        ArrayList<String> images;
        ArrayList<String> originImages;
        ArrayList<String> dragImages;
        Handler handler;
        boolean add;//是否为添加图片

        public MyRunnable(ArrayList<String> images, ArrayList<String> originImages, ArrayList<String> dragImages, Handler handler, boolean add) {
            this.images = images;
            this.originImages = originImages;
            this.dragImages = dragImages;
            this.handler = handler;
            this.add = add;
        }

        @Override
        public void run() {
            SdcardUtils sdcardUtils = new SdcardUtils();
            String filePath;
            Bitmap newBitmap;
            int addIndex = originImages.size() - 1;
            for (int i = 0; i < images.size(); i++) {
                if (images.get(i).contains(StageBaoApplication.getInstance().getString(R.string.glide_plus_icon_string))) {//说明是添加图片按钮
                    continue;
                }
                //压缩
                newBitmap = ImageUtils.compressScaleByWH(images.get(i),
                        DensityUtils.dp2px(StageBaoApplication.getInstance(), 100),
                        DensityUtils.dp2px(StageBaoApplication.getInstance(), 100));
                //文件地址
                if (images.get(i).substring(0, 4).equals("http")) {
                    filePath = images.get(i);
                } else {
                    filePath = sdcardUtils.getSDPATH() + FILE_DIR_NAME + "/"
                            + FILE_IMG_NAME + "/" + String.format("img_%d.jpg", System.currentTimeMillis());
                }
                //保存图片
                ImageUtils.save(newBitmap, filePath, Bitmap.CompressFormat.JPEG, true);
                //设置值
                if (!add) {
                    images.set(i, filePath);
                } else {//添加图片，要更新
                    dragImages.add(addIndex, filePath);
                    originImages.add(addIndex++, filePath);
                }
            }
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    }

    private MyHandler myHandler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private WeakReference<Activity> reference;

        public MyHandler(Activity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ArtistEditPersonWorkActivity activity = (ArtistEditPersonWorkActivity) reference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        activity.postArticleImgAdapter.notifyDataSetChanged();
                        break;
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        myHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void initUI() {
        super.initUI();
        StatusBarUtil.setWindowStatusBarColor(this, R.color.colorGray_F8);
        tvTitle.setText("个人代表作");

//        tvRight.setText("保存");
        tvRight.setVisibility(View.VISIBLE);

        initData();
        initView();
    }


    Intent intent;

    @OnClick(R.id.tvRight)
    public void saveImgs() {

        List<String> imgs = new ArrayList<>();
        if (dragImages.size() > 0)
            for (int i = 0; i < dragImages.size() - 1; i++) {
                imgs.add(dragImages.get(i));
            }
        Map<String, String> params = new HashMap<>();
        params.put("workType", "3");
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < imgs.size(); i++) {
            Bitmap bitmap = BitmapFactory.decodeFile(imgs.get(i));
            buffer.append(bitmap2StrByBase64(bitmap) + ",");
            params.put("photoImgFile" + i, bitmap2StrByBase64(bitmap));
            bitmap.recycle();
        }

        String s = buffer.toString();
        s = s.substring(0, s.length() - 1);
        artistRestUsage.addRepresentativeWork(addRepresentativeWork, params);
        intent = new Intent();
        intent.putStringArrayListExtra("imgs", (ArrayList<String>) imgs);

//        Intent intent = new Intent();
//        List<String> imgs = new ArrayList<>();
//        if (dragImages.size() > 0)
//            for (int i = 0; i < dragImages.size() - 1; i++) {
//                imgs.add(dragImages.get(i));
//            }
//
//
//        intent.putStringArrayListExtra("imgs", (ArrayList<String>) imgs);
//        setResult(Util.TO_ADD_PHOTO, intent);
//        finish();
//        artistRestUsage.addRepresentativeWork();
    }


    /**
     * 通过Base32将Bitmap转换成Base64字符串
     *
     * @param bit
     * @return
     */
    public String bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return
//                "data:image/" + type + ";base64," +
                Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    @Override
    public void refreshUI(int taskId, MSG msg) {
        if (taskId == addRepresentativeWork) {
            if ("保存成功".equals(msg.getMessage())) {
                setResult(Util.TO_ADD_PHOTO, intent);
                finish();
            }
            dismissProgressDialog();
        }
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_edit_person_work;
    }


}
